﻿using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ALDIOrganizer.Properties;
using Generator;

namespace ALDIOrganizer
{    
    public partial class MainForm : Form
    {
        DataGridViewTextBoxColumn colHolidayEmployees_name;
        DataGridViewTextBoxColumn colHolidayEmployees_allowance;

        /// <summary>
        /// Currently edited (viewed) / cached Rota, databound to SheetRota SheetView
        /// </summary>
        Rota CurrentRota;

        /// <summary>
        /// Currently edited (viewed) / cached Template, databound to SheetTemplate SheetView
        /// </summary>
        Template CurrentTemplate;

        
        public MainForm()
        {
            // Thread.CurrentThread.CurrentUICulture = new CultureInfo("pl-PL");
            InitializeComponent();            

            
        }

        private bool Quit()
        {
            var anyChanges = (CurrentRota != null &&
                CurrentTemplate != null &&
                Program.CurrentFile != null) &&
                (CurrentRota.Modified ||
                CurrentTemplate.Modified ||
                Program.CurrentFile.Modified);
            if (!anyChanges)
            {
                if (MessageBox.Show(
                    Resources.MESSAGEBOX_QUESTION_QuitProgram_MESSAGE,
                    Resources.MESSAGEBOX_QUESTION_QuitProgram_CAPTION,
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) != DialogResult.Yes)
                    return false;
            }            
            if (!CurrentRota.OKLeaving() ||
                !CurrentTemplate.OKLeaving() ||
                !Program.CurrentFile.OKLeaving())
            {
                return false;
            }            
            Program.Quit();
            return true;
        }
                
                                
        public Control[] ctrlsToHideOnPanel2;

        private void IconTabs()
        {
            Image calendar = Resources.cal_16x16;
            Image rota = Resources.table_16x16;            
            Image staff = Resources.user_16x16;            
            Image holidays = Resources.sun;
            Image requests = Resources.request;            

            var icons = new ImageList();
            icons.Images.Add(calendar);            
            icons.Images.Add(rota);            
            icons.Images.Add(staff);
            icons.Images.Add(holidays);
            icons.Images.Add(requests);            
            tbMain.ImageList = icons;

            tpCalendar.ImageIndex = 0;
            tpRota.ImageIndex = 1;            
            tpStaff.ImageIndex = 2;
            tpHolidays.ImageIndex = 3;
            tpRequests.ImageIndex = 4;            
        }

        private void Set_sheetHolidayEmployeesColumns()
        {
            dgridHolidayEmployees.AutoGenerateColumns = false;

            colHolidayEmployees_name = new DataGridViewTextBoxColumn
                                           {
                                               DataPropertyName = "name",
                                               AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
                                               FillWeight = 55,
                                               HeaderText =
                                                   Resources.FORM_MAINFORM_dgridHolidayEmployees_EmployeeHeaderText
                                           };

            colHolidayEmployees_allowance = new DataGridViewTextBoxColumn
                                                {
                                                    DataPropertyName = "allowance",
                                                    AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill,
                                                    FillWeight = 45,
                                                    HeaderText =
                                                        Resources.
                                                        FORM_MAINFORM_dgridHolidayEmployees_AllowanceHeaderText.Replace(
                                                            @"\n",
                                                            Environment.NewLine)
                                                };

            dgridHolidayEmployees.Columns.Add(colHolidayEmployees_name);
            dgridHolidayEmployees.Columns.Add(colHolidayEmployees_allowance);
        }

        

        /// <summary>
        /// Basically
        /// </summary>        
        void cbTemplate_Enter(object sender, EventArgs e)
        {
            if (Program.Logged.CanEditRota(CurrentRota.Monday))
            {
                return;
            }
            cbTemplate.Enabled = false;
            cbTemplate.Enabled = true;
        }    

        private void formRotaEditor_Load(object sender, EventArgs e)
        {
            StartUp();            
        }

        void btnSaveRota_Click(object sender, EventArgs e)
        {
            SaveRota();            
        }

        void btnDeleteTemplate_Click(object sender, EventArgs e)
        {
            if (CurrentTemplate.Name != Template.DefaultName)
            {
                DeleteTemplate(CurrentTemplate.Name);
                return;
            }
            // else
            MessageBox.Show(
                Resources.MESSAGEBOX_ERROR_DefaultTemplateUndeletable_MESSAGE,
                Resources.MESSAGEBOX_ERROR_DefaultTemplateUndeletable_CAPTION,
                MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }

        void btnNewTemplate_Click(object sender, EventArgs e)
        {
            CreateNewTemplate();
        }

        void btnSaveTemplate_Click(object sender, EventArgs e)
        {
            SaveTemplate();
        }


        void cbTemplate_SelectedValueChanged(object sender, EventArgs e)
        {   
            if ((cbTemplate.Tag.GetType() == typeof(bool) &&
                (bool)cbTemplate.Tag) ||  // ignore selected value changed
                cbTemplate.SelectedValue == null)
            {
                return;
            }                        
            if (CurrentTemplate != null &&
                cbTemplate.SelectedValue.ToString() == CurrentTemplate.Name)
            {
                return;
            }            
            ChangeTemplate(cbTemplate.SelectedValue.ToString());
        }

        private void SetTabPageText(
            TabPage pTabPage,
            int pCount,
            string pTextIfNone,
            string pTextIfSome)
        {
            if (pCount > 0)
            {
                pTabPage.Text = pTextIfSome.Replace(
                    "#",
                    pCount.ToString());
            }
            else
            {
                pTabPage.Text = pTextIfNone;
            }
        }

        private void SetTitlesOfHolidaysAndRequestsTabs(bool pHolidayTab, bool pRequestTab)
        {            
            if (pHolidayTab)
            {
                SetTabPageText(
                    tpHolidays,
                    SQLiteAccess.GetPendingHolidaysCount((int)cbYear.SelectedValue),
                    Resources.TABPAGE_Holidays_NoPending,
                    Resources.TABPAGE_Holidays_Pending);
            }

            if (pRequestTab)
            {                
                
                SetTabPageText(
                    tpRequests,
                    dgridRequestsPending.Rows.Count, /* surely a bit ugly, referring to an UI control
                                                      * (while retrieving analogical number for pending holidays
                                                      * from SQLite class - inconsistent), may need to later get back to it */
                    Resources.TABPAGE_Requests_NoPending,
                    Resources.TABPAGE_Requests_Pending);                    
            }
        }


        private void tbMain_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (tbMain.TabPages[e.TabPageIndex].Enabled)
            {
                return;
            }
            MessageBox.Show(
                Resources.MESSAGEBOX_INFO_InsufficientPrivilegesTab_MESSAGE,
                Resources.MESSAGEBOX_INFO_InsufficientPrivilegesTab_CAPTION,
                MessageBoxButtons.OK,
                MessageBoxIcon.Stop);
            e.Cancel = true;            
        }

                

        

        
        


        

        private void btnHideTemplate_Click(object sender, EventArgs e)
        {

            SaveSplitterPanelPosition();

            SuspendLayout();
            

            foreach (var c in ctrlsToHideOnPanel2)
            {
                c.Visible = false;
                c.Enabled = false;
            }
            
            btnShowTemplate.Visible = true;
            btnShowTemplate.Enabled = true;

            splPanels.SplitterDistance = splPanels.Height - splPanels.Panel2MinSize;

            this.splPanels.IsSplitterFixed = true;

            AdjustSheetTempRotaHeight();
            this.ResumeLayout();
        }

        private void btnShowTemplate_Click(object sender, EventArgs e)
        {
            SuspendLayout();
            foreach (var c in ctrlsToHideOnPanel2)
            {
                c.Visible = true;
                c.Enabled = true;
            }

            btnShowTemplate.Visible = false;
            btnShowTemplate.Enabled = false;

            splPanels.IsSplitterFixed = false;
            RetrieveSplitPanelProportions();

            AdjustSheetTempRotaHeight();
            
            ResumeLayout();
        }
                

        private void sheetTempRota_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {   
            
            AdjustSheetTempRotaHeight();
        }        
        
        private void sheetTempRota_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            // 
            layoutAdjustWidthOfSheets(false);            
        }

        private void sheetTempRota_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            AdjustSheetTempRotaHeight();
        }
                        
        private static Parameters lastUsed;
        public static int lastUsedAddEmpToTemp;

        

        

        private void btnAddEmployee_Click(object sender, EventArgs e)
        {
            AddEmployee();
        }

        // listbox height doesn't change "smoothly", hence we manually adjust the UI so that the controls are in line
        private void tblStoreStaff_Resize(object sender, EventArgs e)
        {
            tblStaffManageButtons.Height = lbStaffMembers.Bottom + btnChangeContract.Margin.Bottom;
        }

        

        private void btnEditEmployee_Click(object sender, EventArgs e)
        {
            EditEmployee();
        }


        private void tblManageHolidays_Resize(object sender, EventArgs e)
        {
            /* NOTE: I know about Dock property, but When it'pShift On,
             * the comboBox is not centered vertically On the panel, which looks bad.
             * If I use Anchor, it doesn't resize itself horizontally.
             * so this is the fix. 
             * 
             * by the way (interestingly) GetColumnWidths method is not intellisense,
             * whatever the reason. */
            cbYear.Width = tblYear.GetColumnWidths()[1];

        }


        private void btnPrev_Click(object sender, EventArgs e)
        {
            GoToNeighbouringRota(RelativePosition.Previous);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            GoToNeighbouringRota(RelativePosition.Next);
        }

        private void SwitchToTab(TabPage pTab)
        {
            if (tbMain.Contains(pTab))
            {
                tbMain.SelectedTab = pTab;
            }
        }

        private void btnInventories_Click(object sender, EventArgs e)
        {
            // SQLiteAccess.DeleteEmployee(1);
            SetStatusOnCurrentRota(SpecialDayStatus.Inventory);
        }
                

        private void btnShutDays_Click(object sender, EventArgs e)
        {
            SetStatusOnCurrentRota(SpecialDayStatus.Shut);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = !Quit();
                if (e.Cancel)
                {
                    return;
                }
            }
            Application.Exit();            
        }

        internal void DisableFormClosing()
        {
            FormClosing -= MainForm_FormClosing;
        }
        

    }

}
